Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[11.x] Add getConnection() Method to Factory Class for Retrieving Database Connection #53237

Merged
merged 5 commits into from
Oct 21, 2024

Conversation

jonathanpmartins
Copy link
Contributor

@jonathanpmartins jonathanpmartins commented Oct 19, 2024

Context: I’m proposing a small but useful addition to the Illuminate\Database\Eloquent\Factories\Factory class by introducing a getConnection() method. This method allows developers to retrieve the database connection used by a factory when generating models.

Problem: Currently, there’s no easy way to access the database connection associated with a factory. In certain scenarios, especially when working with factories in testing environments on multi-database setups, having access to this connection would be valuable. This change makes it easier to inspect and work with the connection, especially when debugging or ensuring models are generated with the correct database connection.

Solution: I have added the following method to the Factory class:

/**
 * Get the database connection that is used to generate models.
 *
 * @return string
 */
public function getConnection()
{
    return $this->connection;
}

This method will simply return the connection that was set when the factory instance was created.

Tests: I have added a test case that verifies the behavior of the new getConnection() method. The test sets a custom connection on the factory and ensures that the getter retrieves the correct connection:

public function test_get_connection_used_to_create_a_model()
{
    $factory = FactoryTestUserFactory::new()->connection('custom-connection');

    $this->assertSame('custom-connection', $factory->getConnection());
}

I believe this small enhancement could be beneficial for those working with Laravel factories in environments where multiple database connections are used, as it provides a simple way to inspect and work with connections at the factory level.

Thank you for your consideration, and I’m happy to discuss any feedback or make any adjustments as needed.

@jonathanpmartins jonathanpmartins changed the title Add getConnection() Method to Factory Class for Retrieving Database Connection [11.x] Add getConnection() Method to Factory Class for Retrieving Database Connection Oct 19, 2024
@taylorotwell taylorotwell merged commit 57a35ec into laravel:11.x Oct 21, 2024
21 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants